package day07;

import java.io.*;
import java.net.Socket;
import java.util.Objects;
import java.util.Scanner;

/**
 * @author zouran
 * createDate：2024/7/3  19:57
 */
public class SocketClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 10000);
        new Thread(() -> {
            try {
                InputStream in = socket.getInputStream();
                OutputStream out = socket.getOutputStream();
                while (true) {
                    if (sendMessage(out))
                        break;
                    if (handleMessage(in))
                        break;
                }
                in.close();
                out.close();
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }

    public static boolean handleMessage(InputStream in) {
        String message;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            message = reader.readLine();
            System.out.println("收到信息:" + message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Objects.equals("bye", message);
    }

    public static boolean sendMessage(OutputStream out) {
        String message;
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入发送信息:");
            message = scanner.nextLine();
            writer.write(message + '\n');
            writer.flush();
            System.out.println("发送成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Objects.equals("bye", message);
    }
}
